<?php


namespace App\Http\Controllers\Backend;

use App\Http\Requests\Company\DeviceRequest;
use App\Services\Business\Models\Device;
use App\Zesow\YingShi;
use GuzzleHttp\Client;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DeviceController extends BaseController
{


    public function __construct()
    {
    }

    public function index(Request $request)
    {
        $companyId = $this->loginCompanyId();
        $serial = $request->input('serial', '');
        $name = $request->input('name', 0);
     
        $devices = Device::query()
            ->when($name, function ($query) use ($name) {
                return $query->where('name', 'like', '%' . $name . '%');
            })
            ->when($serial, function ($query) use ($serial) {
                return $query->where('subserial_number',$serial);
            })

            ->where('company_id',$companyId)
            ->orderByDesc('created_at')
            ->paginate($request->input('size', 10));
        return $this->successData(compact('devices'));
    }


    /**
     * @param DeviceRequest $request
     * @param device $device
     * @return JsonResponse
     */
    public function store(DeviceRequest $request, Device $device)
    {

        $data = $request->filldata();
        $serialNumber = $data['serial_number']??'';
        $validateCode = $data['validate_code']??'';
        $app = new YingShi();
        $result = $app->add($serialNumber,$validateCode);
        if ($result['code'] !="200") {
            return  $this->error(__($result['msg']));
        }
        $device->fill($data);
        $device->save();
        return $this->success(__('添加设备成功'));
    }


    /**
     * 风格编辑
     * @param $id
     * @return JsonResponse
     */
    public function edit($id)
    {

        $device = Device::query()->where('id',$id)->first();
        return $this->successData(compact('device'));
    }


    /**
     * 风格更新
     * @param DeviceRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function update(DeviceRequest $request, $id)
    {

        $device = Device::query()->where('id',$id)->first();
        $data = $request->filldata();
        $device->fill($data);
        $device->save();

        return $this->success(__('更新设备成功'));
    }


    /**
     * 设备删除
     * @param $id
     * @return JsonResponse
     */
    public function delete($id)
    {


        $device =  Device::query()->where('id',$id)->first();
        $app = new YingShi();
        if ($device->decorates()->exists()) {
            return  $this->error(__('不能删除'));
        }
       $result = $app->delete($device->serial_number);
        if ($result['code'] !="200") {
            return  $this->error(__($result['msg']));
        }
        $device->delete();
        return $this->success(__('删除成功'));
    }





}